<?php

class SeoText2Keywords
{
    protected $text;
    protected $keywords = array();
    protected $filter;
    
    public function __construct($text, SeoKeywordFilter $filter = null)
    {
        if(is_array($text)) {
            foreach ($text as $string) {
                $this->text .= ' ' . $string;
            }
        } else {
            $this->text = $text;
        }
        $this->filter = $filter;
        $this->generate();
    }
    
    protected function generate()
    {
        if(preg_match_all("/([\p{L}\p{N}]+)/ui", $this->text, $words)) {
            foreach ($words[0] as $word) {
                if($this->filter instanceof SeoKeywordFilter && !$this->filter->validate($word)) {
                    continue;
                }
                
                $word = mb_strtolower($word);
                if(!array_key_exists($word, $this->keywords)) {
                    $this->keywords[$word] = 0;
                }
                
                $this->keywords[$word]++; // calculate phrase weight
            }
            
            ksort($this->keywords);
        }
    }
    
    public function __toString()
    {
        return mb_strtolower(implode(' ', array_keys($this->keywords)));
    }
    
    public function getKeywords()
    {
        return array_keys($this->keywords);
    }
}